package com.pjb.springbootjjwt.store;

import com.pjb.springbootjjwt.store.entity.Head;
import com.pjb.springbootjjwt.store.entity.Line;
import com.pjb.springbootjjwt.store.entity.Record;
import com.pjb.springbootjjwt.store.utils.FileUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Function {

    /**
     * 获取状态函数
     *
     * @return
     */
    public static Record get(String sql) throws Exception {
        sql = sql.substring(sql.indexOf("select"));
        sql = sql.replaceAll("select", "");
        String method = sql;
        List<Line> list = new ArrayList<>();
        Line line = new Line();
        String value = getMethod(method
                .replaceAll("\\(", "")
                .replaceAll("\\)", "")).trim();
        line.setData(Collections.singletonList(value));
        list.add(line);

        Head head = Head.toHead(sql.trim());
        return Record.builder().head(head).line(list).build();//.toRecord(head, list);
    }

    private static String getMethod(String method) throws IOException {
        String c = FileUtil.readFile("sys", "@status");
        String[] arr = c.split(";");
        for (String l : arr) {
            String key = l.substring(0, l.indexOf(":")).trim();
            if (key.equals(method.trim())) return l.split(":")[1].trim();
        }
        return method;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(Function.get("select version()"));
        System.out.println(Function.get("select author()"));
    }
}
